﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Web.Hosting;

namespace UDS.Components
{
    /// <summary>
    /// 错误处理函数，用于记录错误日志
    /// </summary>
    public static class Logger
    {
        //记录错误日志位置
        private static string s_logFile;
        private static object s_locker = new object();
        private static StreamWriter s_writer;

        private static string LogFileName
        {
            get
            {
                if (s_logFile == null)
                {
                    var file = ConfigurationManager.AppSettings["LogFile"];
                    if (string.IsNullOrEmpty(file))
                    {
                        file = @"c:\uds_log.txt";
                    }
                    else
                    {
                        file = Utility.ResolvePath(file);
                        Debug.Assert(!string.IsNullOrEmpty(file));
                        if (file[0] == '/' || file[0] == '\\')
                        {
                            file = HostingEnvironment.MapPath(file);
                        }
                    }

                    s_logFile = file;
                }
                return s_logFile;
            }
        }

        /// <summary>
        /// 记录日志至文本文件
        /// </summary>
        /// <param name="message">记录的内容</param>
        public static void Log(string message)
        {
            if (s_writer == null)
            {
                lock (s_locker)
                {
                    if (s_writer == null)
                    {
                        // Ensures the directory exists
                        DirectoryInfo dirInfo = new DirectoryInfo(Path.GetDirectoryName(LogFileName));
                        if (!dirInfo.Exists)
                        {
                            dirInfo.Create();
                        }

                        FileStream fs = new FileStream(LogFileName, FileMode.Append, FileAccess.Write, FileShare.Read);
                        s_writer = new StreamWriter(fs, System.Text.Encoding.UTF8);
                        s_writer.WriteLine();
                        s_writer.WriteLine("=============== Log file opened at {0:yyyy-MM-dd HH:mm:ss} ===============", DateTime.Now);
                        s_writer.Flush();
                    }
                }
            }

            lock (s_locker)
            {
                s_writer.Write("[{0:yyyy-MM-dd HH:mm:ss}] ", DateTime.Now);
                s_writer.WriteLine(message);
                s_writer.Flush();
            }
        }
    }
}